<script setup lang="ts">
  import { onBeforeUnmount, reactive, ref } from 'vue'
  import { getCaptchaReq, registerReq } from '@/api'
  import { message } from 'ant-design-vue'
  import { useRegexp } from '@/hooks/useRegexp'
  import useDebounce from '@/hooks/useDebounce'

  interface FormState {
    username: string
    password: string
    email: string
    captcha: string
  }

  const formState = reactive<FormState>({
    username: '',
    password: '',
    email: '',
    captcha: '',
  })

  const formRef = ref()

  const showRegister = defineModel()

  // 验证码
  const captchaState = reactive({
    isLoading: false,
    isCounting: false,
    count: 20,
  })

  const countDownRef = ref()
  const getCaptcha = useDebounce(async () => {
    // 验证邮箱格式
    if (!formState.email || !useRegexp(formState.email, 'email')) {
      message.error('请输入有效的电子邮件地址')
      return
    }
    captchaState.isLoading = true
    // 请求接口
    try {
      await getCaptchaReq({ email: formState.email, type: 'register' })
      message.info('邮件已发送，若未收到请检查邮箱是否正确')
      // 接口返回后倒计时
      countDownFun()
    } catch (error) {}

    captchaState.isLoading = false
  }, 500)

  // 倒计时
  const countDownFun = () => {
    captchaState.count = 20
    captchaState.isCounting = true
    if (countDownRef.value) clearInterval(countDownRef.value)
    countDownRef.value = setInterval(() => {
      if (captchaState.count > 0) {
        captchaState.count += -1
      } else {
        clearInterval(countDownRef.value)
        captchaState.isCounting = false
      }
    }, 1000)
  }

  // 注册
  const registerFun = useDebounce(() => {
    formRef.value
      .validate()
      .then(async () => {
        const res = await registerReq(formState)
        if (res?.data) {
          message.success('注册成功')
          showRegister.value = false
        }
      })
      .catch(() => {})
  }, 500)

  const validateFun = (rule: any, value: string) => {
    if (!useRegexp(value, rule.field)) {
      return Promise.reject('请输入正确格式')
    }
    return Promise.resolve()
  }

  onBeforeUnmount(() => {
    if (countDownRef.value) {
      clearTimeout(countDownRef.value)
      countDownRef.value = null
    }
  })
</script>

<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="registerForm"
    style="padding: 20px"
  >
    <a-form-item
      name="username"
      :rules="[{ required: true, message: '' }, { validator: validateFun }]"
      label="用户名"
      :validate-trigger="['']"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-input
        v-model:value.trim="formState.username"
        placeholder="5-16位字母、数字或下划线"
      >
        <template #prefix>
          <UserOutlined style="color: rgba(0, 0, 0, 0.6)" />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      name="password"
      :rules="[{ required: true, message: '' }, { validator: validateFun }]"
      label="密码"
      :validate-trigger="['']"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-input-password
        v-model:value.trim="formState.password"
        placeholder="8位以上，大小写字母、数字各至少1个"
      >
        <template #prefix>
          <LockOutlined style="color: rgba(0, 0, 0, 0.6)" />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item
      name="email"
      :rules="[{ required: true, message: '' }, { validator: validateFun }]"
      label="邮箱"
      :validate-trigger="['']"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-input v-model:value.trim="formState.email">
        <template #prefix>
          <MailOutlined style="color: rgba(0, 0, 0, 0.6)" />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      name="captcha"
      :rules="[{ required: true, message: '请输入验证码' }]"
      label="验证码"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-row :gutter="8">
        <a-col :span="18">
          <a-input
            v-model:value.trim="formState.captcha"
            placeholder="6位数字"
          >
            <template #prefix>
              <SafetyOutlined style="color: rgba(0, 0, 0, 0.6)" />
            </template>
          </a-input>
        </a-col>
        <a-col :span="6">
          <a-button
            style="width: 100%"
            :loading="captchaState.isLoading"
            @click="getCaptcha"
            :disabled="captchaState.isLoading || captchaState.isCounting"
          >
            {{
              captchaState.isLoading
                ? ''
                : captchaState.isCounting
                  ? captchaState.count
                  : '获取'
            }}
          </a-button>
        </a-col>
      </a-row>
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button
        type="primary"
        style="width: 200px; height: 40px"
        @click="registerFun"
        >注册</a-button
      >
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less"></style>
